<?php
Yii::import('application.modules.menu.utililies.menuService');

class StorageDetailController extends ControllerBase
{
	public function init() {
            parent::init();
            $this->defaultAction = 'admin';
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new StorageDetail;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Material']))
		{
                    $time = time();
                    $storageModel = new Storage;
                    $storageModel->income_time = $time;
                    $storageModel->by_user = 1;
                    $storageModel->save();
			
                    foreach ($_POST['Material'] as $m => $value){
                        foreach ($value as $k => $v){
                            $quantity = preg_replace('/\\s/', '', $v);
                            if (intval($quantity) != 0){
                                //insert into material request detail
                                $model=new StorageDetail;
                                //$model->recipieid = $_POST['Recipiedetail']['materialid']; //column recipieid in recipiedetail named materialid in create form
                                $model->income_amount = $quantity;
                                $model->material_id = $k;
                                $model->storage_id = $storageModel->storage_id;
                                $model->unit_id = 1;
                                $model->save();
                                
                                //update material quantity
                                $material = Material::model()->find(array(
                                    'condition' => 'materialid = :id',
                                    'params' => array(
                                        ':id' => $k
                                    )
                                ));
                                $material->storagequantity = $material->storagequantity + (int)$quantity;
                                $material->update();
                            }                                
                        }
                    }
                    
                    $this->setMessage('Add Storage Successful');
                    $this->refresh();
		}

                $materialList = Material::model()->findAll();
		$this->render('create',array(
			'model'=>$model,
                        'materialList' => $materialList
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Material']))
		{
                    foreach ($_POST['Material'] as $m => $value){
                        foreach ($value as $k => $v){
                            $quantity = preg_replace('/\\s/', '', $v);                                
                            if (intval($quantity) != 0){
                                $storageDetailModel = StorageDetail::model()->find(array(
                                    'condition' => 'storage_id = :id AND material_id = :materialid',
                                    'params' => array(
                                        ':id' => $_POST['Material']['income_amount'],
                                        ':materialid' => $k,
                                    )
                                ));  

                                //update recipie materials
                                if($storageDetailModel !== null){
                                    $storageDetailModel->updateAll(
                                        array(
                                            'income_amount' => $quantity,
                                            'material_id' => $k
                                        ),
                                        'storage_id = ' . $storageDetailModel->storage_detail_id . ' AND materialid = ' . $k);

                                }else{  //insert new recipie material
                                  $storageDetailModel = new StorageDetail();
                                  $storageDetailModel->material_id = $k;
                                  $storageDetailModel->income_amount = $quantity;
                                  $storageDetailModel->storage_id = $id;
                                  $storageDetailModel->save();
                                }                                    
                            }
                        }
                    }                    
		}
                
                //load material in StorageDetail
                $presetMaterial = StorageDetail::model()->findAll(array(
                    'condition' => 'storage_id = :id',
                    'params' => array(
                        ':id' => $id,
                    )
                ));

                $materialList = Material::model()->findAll();
		$this->render('update',array(
			'model'=>$model,
                        'materialList' => $materialList,
                        'presetMaterial' => $presetMaterial,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new StorageDetail('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['StorageDetail']))
			$model->attributes=$_GET['StorageDetail'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=StorageDetail::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='storage-detail-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
    public function beforeAction($action) {
        parent::beforeAction($action);
        if (Yii::app()->user->id === null)
            $this->redirect(Yii::app()->createUrl('site/login'));
        return true;
        $this->redirect(Yii::app()->createUrl('site/login'));
    }
}
